/*
Copyright (c) 2010 Tiana RAZAFINDRALAMBO

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package;
import StringTools;
import Curl; 
import CurlOpt;
import CurlInfo;
import Xml;

class GAnalytics
{	
	private var email:String;
	private var password:String;
	private var ids:String;
 	private var curl:Curl;
 	private var auth:String;

	static function main()
	{
		
	}
	public function new()
	{		
	}
	public function login(email:String, pwd:String, id:String)
	{
		 
		this.email = email;
		this.password = pwd;
		this.ids = id;

		var ch = Curl.init();
		var data = {accountType:'GOOGLE',
			    Email:this.email,
			    Passwd:this.password,
			    source:'CLI_GAnalytics',
			    service:'analytics'
			    };

						  
		Curl.setopt(ch, CurlOpt.URL, "https://www.google.com/accounts/ClientLogin");
		Curl.setopt(ch, CurlOpt.FOLLOWLOCATION, true);
		Curl.setopt(ch, CurlOpt.SSL_VERIFYPEER, 0);
		Curl.setopt(ch, CurlOpt.POST, true);
		Curl.setopt(ch, CurlOpt.RETURNTRANSFER, true);
		Curl.setopt(ch, CurlOpt.POSTFIELDS, data);

		var hasil = Curl.exec(ch);
		var res = hasil.split("Auth=");

		Curl.close(ch);

		this.auth = res[1];	
	}
	public function getDimensionByMetric(metrics:String, dimensions:String, filters:String="", max:Int = 25, sort:String = "", start:String, end:String = null):Dynamic
	{
		if(end == null) end = start;

                var sort2 = StringTools.replace(StringTools.replace(sort, "asc,",  "ga:"), "desc,", "-ga:" );

                var ch = Curl.init("https://www.google.com/analytics/feeds/data?ids=ga:"+this.ids+"&metrics=ga:"+metrics+"&dimensions=ga:"+dimensions+((filters!="")?"&filters=ga:"+filters:"")+"&sort="+sort2+"&start-date="+start+"&end-date="+end+"&max-results="+max);
		 
                untyped __php__("$header[] = 'Authorization: GoogleLogin auth='.$this->auth");

                Curl.setopt(ch, CurlOpt.SSL_VERIFYPEER,0);
                Curl.setopt(ch, CurlOpt.HTTPHEADER, untyped __php__("$header"));
                Curl.setopt(ch, CurlOpt.RETURNTRANSFER, true);
                Curl.setopt(ch, CurlOpt.HEADER, false);

                var response = Curl.exec(ch);
                var infos = Curl.getinfo(ch);

                Curl.close(ch);

                if(untyped __php__("$infos['http_code']!=200"))
                {
                	trace(response); 
                	return null;
                }
                else
                { 
                	var xml_response = StringTools.replace(response, 'dxp:', '');
 			var xml_object = Xml.parse(xml_response);
 			 
 			var fast = new haxe.xml.Fast(xml_object.firstElement());
 			var entries = fast.nodes.entry;

 			var DATA = [];
                	var LABEL = [];
 			for(entry in entries)
 			{
 				DATA.push(entry.node.metric.att.value);
 				LABEL.push(entry.node.dimension.att.value); 
 			}  
			return {label:LABEL, data:DATA};  
                }
	}
	public function getMetric(metric:String, start:String, end:String = null)
	{
		if(end==null) end = start;
			
		var ch = Curl.init("https://www.google.com/analytics/feeds/data?ids=ga:"+this.ids+ "&metrics=ga:"+metric+"&start-date="+start+"&end-date="+end);  
  
		untyped __php__("$header[] = 'Authorization: GoogleLogin auth='.$this->auth");

		Curl.setopt(ch, CurlOpt.SSL_VERIFYPEER, 0);  
		Curl.setopt(ch, CurlOpt.HTTPHEADER, untyped __php__("$header"));  
		Curl.setopt(ch, CurlOpt.RETURNTRANSFER, true);  
		Curl.setopt(ch, CurlOpt.HEADER, false); 
		  
		var response = Curl.exec(ch); 
		var infos = Curl.getinfo(ch);
		Curl.close(ch);

		if(untyped __php__("$infos['http_code']!=200"))
                {
			trace(response);
			return null;
		}
		
		var xml_response = StringTools.replace(response, 'dxp:', '');
 		var xml_object = Xml.parse(xml_response);

		var fast = new haxe.xml.Fast(xml_object.firstElement());
		var entry = fast.nodes.entry.first();
		return (entry.node.metric.att.value!='')? entry.node.metric.att.value : '0';
	}
	
}
